package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.dto.UsedCarEvaluationRequest;
import com.zhentao.dto.UsedCarEvaluationResponse;
import com.zhentao.mapper.CarBrandMapper;
import com.zhentao.mapper.CarModelMapper;
import com.zhentao.mapper.UsedCarEvaluationMapper;
import com.zhentao.pojo.CarBrand;
import com.zhentao.pojo.CarModel;
import com.zhentao.pojo.UsedCarEvaluation;
import com.zhentao.service.UsedCarEvaluationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 二手车评估服务实现类
 */
@Slf4j
@Service
public class UsedCarEvaluationServiceImpl implements UsedCarEvaluationService {
    
    @Autowired
    private UsedCarEvaluationMapper evaluationMapper;
    
    @Autowired
    private CarBrandMapper brandMapper;
    
    @Autowired
    private CarModelMapper modelMapper;
    
    @Override
    public UsedCarEvaluationResponse createEvaluation(UsedCarEvaluationRequest request) {
        try {
            // 创建评估记录
            UsedCarEvaluation evaluation = new UsedCarEvaluation();
            evaluation.setUserId(1L); // 临时用户ID，实际应该从登录信息获取
            evaluation.setLicensePlate(request.getLicensePlate());
            evaluation.setBrand(request.getBrand());
            evaluation.setModel(request.getModel());
            evaluation.setYear(request.getYear());
            evaluation.setMileage(request.getMileage());
            evaluation.setEngineDisplacement(request.getEngineDisplacement());
            evaluation.setTransmission(request.getTransmission());
            evaluation.setFuelType(request.getFuelType());
            evaluation.setColor(request.getColor());
            evaluation.setConditionRating(request.getConditionRating());
            evaluation.setExteriorCondition(request.getExteriorCondition());
            evaluation.setInteriorCondition(request.getInteriorCondition());
            evaluation.setMechanicalCondition(request.getMechanicalCondition());
            evaluation.setAccidentHistory(request.getAccidentHistory());
            evaluation.setAccidentDescription(request.getAccidentDescription());
            evaluation.setMaintenanceHistory(request.getMaintenanceHistory());
            evaluation.setStatus(1);
            evaluation.setEvaluationTime(new Date());
            
            // 计算评估价值
            calculateEvaluationValue(evaluation);
            
            // 保存评估记录
            evaluationMapper.insert(evaluation);
            
            // 构建响应
            return buildEvaluationResponse(evaluation);
            
        } catch (Exception e) {
            log.error("创建评估失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建评估失败: " + e.getMessage());
        }
    }
    
    @Override
    public UsedCarEvaluationResponse getEvaluationDetail(Long id) {
        try {
            UsedCarEvaluation evaluation = evaluationMapper.selectById(id);
            if (evaluation == null) {
                throw new RuntimeException("评估记录不存在");
            }
            
            return buildEvaluationResponse(evaluation);
            
        } catch (Exception e) {
            log.error("获取评估详情失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取评估详情失败: " + e.getMessage());
        }
    }
    
    @Override
    public IPage<UsedCarEvaluation> getEvaluationPage(Integer pageNum, Integer pageSize, Long userId) {
        try {
            Page<UsedCarEvaluation> page = new Page<>(pageNum, pageSize);
            QueryWrapper<UsedCarEvaluation> queryWrapper = new QueryWrapper<>();
            
            if (userId != null) {
                queryWrapper.eq("user_id", userId);
            }
            
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("evaluation_time");
            
            return evaluationMapper.selectPage(page, queryWrapper);
            
        } catch (Exception e) {
            log.error("分页查询评估记录失败: {}", e.getMessage(), e);
            throw new RuntimeException("分页查询评估记录失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<UsedCarEvaluation> getUserEvaluationHistory(Long userId) {
        try {
            QueryWrapper<UsedCarEvaluation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("evaluation_time");
            queryWrapper.last("LIMIT 10");
            
            return evaluationMapper.selectList(queryWrapper);
            
        } catch (Exception e) {
            log.error("获取用户评估历史失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取用户评估历史失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean deleteEvaluation(Long id) {
        try {
            UsedCarEvaluation evaluation = new UsedCarEvaluation();
            evaluation.setId(id);
            evaluation.setStatus(0);
            evaluation.setUpdateTime(new Date());
            
            return evaluationMapper.updateById(evaluation) > 0;
            
        } catch (Exception e) {
            log.error("删除评估记录失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除评估记录失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<String> getPopularBrands(Integer limit) {
        try {
            QueryWrapper<CarBrand> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("popularity");
            queryWrapper.last("LIMIT " + limit);
            
            List<CarBrand> brands = brandMapper.selectList(queryWrapper);
            return brands.stream()
                    .map(CarBrand::getBrandName)
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取热门品牌失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取热门品牌失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<String> getModelsByBrand(String brand) {
        try {
            QueryWrapper<CarModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("popularity");
            
            List<CarModel> models = modelMapper.selectList(queryWrapper);
            return models.stream()
                    .map(CarModel::getModelName)
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取品牌车型失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取品牌车型失败: " + e.getMessage());
        }
    }
    
    @Override
    public UsedCarEvaluationResponse quickEvaluation(String brand, String model, Integer year, Double mileage) {
        try {
            // 创建简化版评估请求
            UsedCarEvaluationRequest request = new UsedCarEvaluationRequest();
            request.setBrand(brand);
            request.setModel(model);
            request.setYear(year);
            request.setMileage(BigDecimal.valueOf(mileage));
            request.setConditionRating(BigDecimal.valueOf(8.0)); // 默认良好车况
            
            return createEvaluation(request);
            
        } catch (Exception e) {
            log.error("快速评估失败: {}", e.getMessage(), e);
            throw new RuntimeException("快速评估失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算评估价值
     */
    private void calculateEvaluationValue(UsedCarEvaluation evaluation) {
        try {
            // 基础价格（根据品牌和车型）
            BigDecimal basePrice = getBasePrice(evaluation.getBrand(), evaluation.getModel());
            
            // 车龄折旧
            BigDecimal ageDepreciation = calculateAgeDepreciation(evaluation.getYear());
            
            // 里程折旧
            BigDecimal mileageDepreciation = calculateMileageDepreciation(evaluation.getMileage());
            
            // 车况调整
            BigDecimal conditionAdjustment = calculateConditionAdjustment(evaluation.getConditionRating());
            
            // 事故历史调整
            BigDecimal accidentAdjustment = calculateAccidentAdjustment(evaluation.getAccidentHistory());
            
            // 计算最终价值
            BigDecimal estimatedValue = basePrice
                    .multiply(ageDepreciation)
                    .multiply(mileageDepreciation)
                    .multiply(conditionAdjustment)
                    .multiply(accidentAdjustment)
                    .setScale(2, RoundingMode.HALF_UP);
            
            // 设置评估结果
            evaluation.setEstimatedValue(estimatedValue);
            evaluation.setValueRangeMin(estimatedValue.multiply(BigDecimal.valueOf(0.9)));
            evaluation.setValueRangeMax(estimatedValue.multiply(BigDecimal.valueOf(1.1)));
            
            // 构建评估因素JSON
            Map<String, Object> factors = new HashMap<>();
            factors.put("basePrice", basePrice);
            factors.put("ageDepreciation", ageDepreciation);
            factors.put("mileageDepreciation", mileageDepreciation);
            factors.put("conditionAdjustment", conditionAdjustment);
            factors.put("accidentAdjustment", accidentAdjustment);
            
            evaluation.setEvaluationFactors(com.alibaba.fastjson2.JSON.toJSONString(factors));
            
        } catch (Exception e) {
            log.error("计算评估价值失败: {}", e.getMessage(), e);
            // 设置默认值
            evaluation.setEstimatedValue(BigDecimal.valueOf(10.0));
            evaluation.setValueRangeMin(BigDecimal.valueOf(9.0));
            evaluation.setValueRangeMax(BigDecimal.valueOf(11.0));
        }
    }
    
    /**
     * 获取基础价格
     */
    private BigDecimal getBasePrice(String brand, String model) {
        // 这里应该从数据库查询，暂时使用硬编码
        Map<String, Map<String, BigDecimal>> priceMap = new HashMap<>();
        
        Map<String, BigDecimal> vwModels = new HashMap<>();
        vwModels.put("朗逸", BigDecimal.valueOf(12.0));
        vwModels.put("帕萨特", BigDecimal.valueOf(20.0));
        vwModels.put("途观L", BigDecimal.valueOf(25.0));
        priceMap.put("大众", vwModels);
        
        Map<String, BigDecimal> toyotaModels = new HashMap<>();
        toyotaModels.put("卡罗拉", BigDecimal.valueOf(14.0));
        toyotaModels.put("凯美瑞", BigDecimal.valueOf(22.0));
        toyotaModels.put("RAV4", BigDecimal.valueOf(20.0));
        priceMap.put("丰田", toyotaModels);
        
        Map<String, BigDecimal> hondaModels = new HashMap<>();
        hondaModels.put("雅阁", BigDecimal.valueOf(20.0));
        hondaModels.put("CR-V", BigDecimal.valueOf(22.0));
        priceMap.put("本田", hondaModels);
        
        return priceMap.getOrDefault(brand, new HashMap<>())
                .getOrDefault(model, BigDecimal.valueOf(15.0));
    }
    
    /**
     * 计算车龄折旧
     */
    private BigDecimal calculateAgeDepreciation(Integer year) {
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        int age = currentYear - year;
        
        if (age <= 1) return BigDecimal.valueOf(0.95);
        if (age <= 3) return BigDecimal.valueOf(0.85);
        if (age <= 5) return BigDecimal.valueOf(0.75);
        if (age <= 8) return BigDecimal.valueOf(0.60);
        if (age <= 10) return BigDecimal.valueOf(0.50);
        return BigDecimal.valueOf(0.30);
    }
    
    /**
     * 计算里程折旧
     */
    private BigDecimal calculateMileageDepreciation(BigDecimal mileage) {
        if (mileage.compareTo(BigDecimal.valueOf(5)) <= 0) return BigDecimal.valueOf(0.95);
        if (mileage.compareTo(BigDecimal.valueOf(10)) <= 0) return BigDecimal.valueOf(0.90);
        if (mileage.compareTo(BigDecimal.valueOf(15)) <= 0) return BigDecimal.valueOf(0.80);
        if (mileage.compareTo(BigDecimal.valueOf(20)) <= 0) return BigDecimal.valueOf(0.70);
        return BigDecimal.valueOf(0.60);
    }
    
    /**
     * 计算车况调整
     */
    private BigDecimal calculateConditionAdjustment(BigDecimal conditionRating) {
        if (conditionRating.compareTo(BigDecimal.valueOf(9)) >= 0) return BigDecimal.valueOf(1.0);
        if (conditionRating.compareTo(BigDecimal.valueOf(8)) >= 0) return BigDecimal.valueOf(0.95);
        if (conditionRating.compareTo(BigDecimal.valueOf(7)) >= 0) return BigDecimal.valueOf(0.90);
        if (conditionRating.compareTo(BigDecimal.valueOf(6)) >= 0) return BigDecimal.valueOf(0.85);
        return BigDecimal.valueOf(0.80);
    }
    
    /**
     * 计算事故调整
     */
    private BigDecimal calculateAccidentAdjustment(Integer accidentHistory) {
        return accidentHistory == 1 ? BigDecimal.valueOf(0.85) : BigDecimal.valueOf(1.0);
    }
    
    /**
     * 构建评估响应
     */
    private UsedCarEvaluationResponse buildEvaluationResponse(UsedCarEvaluation evaluation) {
        UsedCarEvaluationResponse response = new UsedCarEvaluationResponse();
        response.setId(evaluation.getId());
        response.setLicensePlate(evaluation.getLicensePlate());
        response.setBrand(evaluation.getBrand());
        response.setModel(evaluation.getModel());
        response.setYear(evaluation.getYear());
        response.setMileage(evaluation.getMileage());
        response.setConditionRating(evaluation.getConditionRating());
        response.setEstimatedValue(evaluation.getEstimatedValue());
        response.setValueRangeMin(evaluation.getValueRangeMin());
        response.setValueRangeMax(evaluation.getValueRangeMax());
        response.setEvaluationNotes(evaluation.getEvaluationNotes());
        response.setEvaluationTime(evaluation.getEvaluationTime());
        response.setMarketReferencePrice(evaluation.getEstimatedValue());
        response.setPriceTrend("稳定");
        response.setRecommendations("建议在" + evaluation.getValueRangeMin() + "-" + evaluation.getValueRangeMax() + "万元之间进行交易");
        
        // 构建评估因素详情
        List<UsedCarEvaluationResponse.EvaluationFactorDetail> factors = new ArrayList<>();
        
        UsedCarEvaluationResponse.EvaluationFactorDetail factor1 = new UsedCarEvaluationResponse.EvaluationFactorDetail();
        factor1.setFactorName("车龄");
        factor1.setFactorValue((Calendar.getInstance().get(Calendar.YEAR) - evaluation.getYear()) + "年");
        factor1.setWeight(BigDecimal.valueOf(0.25));
        factor1.setImpact("中等");
        factor1.setDescription("车龄对价值影响较大");
        factors.add(factor1);
        
        UsedCarEvaluationResponse.EvaluationFactorDetail factor2 = new UsedCarEvaluationResponse.EvaluationFactorDetail();
        factor2.setFactorName("里程数");
        factor2.setFactorValue(evaluation.getMileage() + "万公里");
        factor2.setWeight(BigDecimal.valueOf(0.20));
        factor2.setImpact("中等");
        factor2.setDescription("里程数直接影响车辆价值");
        factors.add(factor2);
        
        UsedCarEvaluationResponse.EvaluationFactorDetail factor3 = new UsedCarEvaluationResponse.EvaluationFactorDetail();
        factor3.setFactorName("车况");
        factor3.setFactorValue(evaluation.getConditionRating() + "分");
        factor3.setWeight(BigDecimal.valueOf(0.30));
        factor3.setImpact("高");
        factor3.setDescription("车况是评估的重要因素");
        factors.add(factor3);
        
        response.setEvaluationFactors(factors);
        
        return response;
    }
}
